package org.example.springoauth2.securitycommon.config;

import cn.hutool.core.util.StrUtil;
import org.example.springoauth2.securitycommon.util.TenantHolder;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 租户拦截器
 *
 * @author hzq
 * @date 2021/9/11 17:39
 */
public class TenantHolderFilter extends OncePerRequestFilter implements OrderedFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 从请求头里获取租户id
        String tenantId = httpServletRequest.getHeader("TenantId");
        // 从请求参数里获取
        if (StrUtil.isBlank(tenantId)) {
            tenantId = httpServletRequest.getParameter("TenantId");
        }
        if (StrUtil.isNotBlank(tenantId)) {
            try {
                TenantHolder.set(new Integer(tenantId));
            } catch (NumberFormatException e) {
                // ignored
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
        TenantHolder.remove();
    }

    @Override
    public int getOrder() {
        return SecurityProperties.DEFAULT_FILTER_ORDER - 100;
    }
}
